package com.yxx.service.Impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.yxx.entityModel.dto.BiliUploadDTO;
import com.yxx.service.BilibiliService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.net.URI;


/**
 * B站服务模块
 * @author yuxiangxun
 * @date 2025/2/1
 * @apiNote
 */
@Service
@Slf4j
public class BilibiliServiceImpl implements BilibiliService {
    @Value("${bili-url}")
    private String biliUrl;

    @Resource
    private RestTemplate restTemplate;


    /**
     * 上传图片到B站
     * @param file
     * @param csrf
     * @param data
     * @return
     */
    @Override
    public String uploadBilibiliPicture(MultipartFile file, String csrf, String data) {
        try{
            // 请求头配置
            HttpHeaders headers = new HttpHeaders();
            // cookie 设置为 SESSDATA + data 拼接
            headers.set("Cookie","SESSDATA" + data);
            // content-type 设置为 multipart/form-data
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            // 构建 Multipart 请求体
            MultipartBodyBuilder multipartBodyBuilder = new MultipartBodyBuilder();
            // Multipart 请求体中添加文件字段file_up 值为 file.getResource()
            multipartBodyBuilder.part("file_up", file.getResource());
            // 构造uri 通过UriComponentsBuilder 构建URL，添加 csrf 参数（用于CSRF校验）
            URI uri = UriComponentsBuilder.fromUriString(biliUrl)
                    .queryParam("csrf", csrf)
                    .build()
                    .toUri();
            // 发送 HTTP POST 请求  床底请求体和请求头
            ResponseEntity<String> response = restTemplate.exchange(  uri,
                                    HttpMethod.POST,
                                    new HttpEntity<>(multipartBodyBuilder.build(),headers),
                                    String.class);
            // 处理响应
            // 使用 ObjectMapper 将 JSON 响应反序列化为 BiliUploadDTO 对象
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
            BiliUploadDTO biliUploadDTO = objectMapper.readValue(response.getBody(), BiliUploadDTO.class);
            BiliUploadDTO.UploadData Data = biliUploadDTO.getData();
            if (Data != null) {
                // 从 BiliUploadDTO 中获取图片URL，并将 http 替换为 https
                return Data.getImageUrl().replaceFirst("http", "https");
            }
            return null;
        }catch (Exception e){
            log.error("uploadBilibiliPicture fail, ", e);
            return null;
        }
    }
}














